package com.ecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecommerce.common.CommonEnum;
import com.ecommerce.common.ResultBody;
import com.ecommerce.entity.Shop;
import com.ecommerce.entity.User;
import com.ecommerce.service.ShopService;
import com.ecommerce.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录Controller
 *
 * @author wang
 */
@RestController
@Api(value = "LoginController", tags = {"登录接口"})
@RequestMapping("/login")
@Log4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private ShopService shopService;

    @ApiOperation(value = "登录接口", notes = "登录接口")
    @PostMapping("login")
    public ResultBody login(@RequestBody User user) {
        if (user.getAccount() != null && user.getUserPassword() != null) {
            Long account = user.getAccount();
            String ciphertext = DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes());
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getAccount, account);
            User one = userService.getOne(userWrapper);
            if (one != null) {
                if (one.getUserPassword().equals(ciphertext)) {
                    Map<String, String> returnMap = new HashMap<>(2);
                    returnMap.put("userId", one.getUserId().toString());
                    if (one.getUserType().equals(CommonEnum.SHOP.getCode())) {
                        LambdaQueryWrapper<Shop> shopWrapper = new LambdaQueryWrapper<>();
                        shopWrapper.eq(Shop::getShopAdmin, one.getUserId());
                        returnMap.put("shopId", shopService.getOne(shopWrapper).getShopId().toString());
                    }
                    return ResultBody.ok().message("登录成功").data(returnMap);
                } else {
                    return ResultBody.error().message("密码错误，请确认账号和密码是否正确");
                }
            } else {
                return ResultBody.error().message("该用户不存在");
            }
        } else {
            return ResultBody.error().message("请输入账号和密码");
        }
    }


}
